package util

import (
	"encoding/json"
	"net"
	"strings"
)

func ToJsonStr(v interface{}) string {
	marshal, err := json.Marshal(v)
	if err != nil {
		return ""
	}
	return string(marshal)
}

func ToJsonStrPretty(v interface{}) string {
	marshal, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		return ""
	}
	return string(marshal)
}

func GetIpAddr() string {
	var ipPrefixList = []string{
		"192.168.1.",
		"192.168.0.",
		"192.168.123.",
		"192.168.31.",
		"192.168.",
		"172.",
		"10.",
	}

	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "127.0.0.1"
	}

	for _, ipPrefix := range ipPrefixList {
		for _, addr := range addrs {
			addrStr := addr.String()
			if strings.HasPrefix(addrStr, ipPrefix) {
				if strings.Contains(addrStr, "/") {
					return addrStr[0:strings.Index(addrStr, "/")]
				} else {
					return addrStr
				}
			}
		}
	}

	return "127.0.0.1"
}
